/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cassandrawindow;

import count.FraudCountByGuid;
import count.FraudGuidInSecRangeResult;
import countdate.FraudCountByGuidInDate;
import countdate.FraudGuidInDateRangeResult;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
import org.apache.log4j.xml.DOMConfigurator;
import util.ConfigUtil;

public class HandleFraudClickByDay {
    public static final String KEYSPACE                             =   "AdsData";
    public static final String ColumFamly                           =   "BannerViewCountCf";
    public static final String ColumFamlyBannerClickCountCf             =   "BannerClickCountCf";
    public static final String ColumFamlyBannerViewCountCf              =   "BannerViewCountCf";

    public static final String ColumFamlyCampaignClickCountCf           =   "CampaignCountCf";
    public static final String ColumFamlyCampaignViewCountCf            =   "CampaignViewCountCf";

    public static final String ColumFamlyCampaignIPCountCf              =   "CampaignIpCountCf";

    public static final String SuperColumFamlyCampaignGuidClick         =   "Guid_Click_Super_Cf";
    
    public static final String ColumFamlyGuidDataContentBanneridData    =   "GuidDate_Content_Bannerid_DataCF";
    public static final String FRAUDCLICKKEYSPACE                       =   "FraudKs";

    public static long checkFraudClickbyDay   =   0;
    
    public void handleData() throws ParseException, InterruptedException, IOException
    {
        long first_time = System.currentTimeMillis();
        int count = 0;
        try {            
            CassandraAction cassAct = new CassandraAction(ACCOUNT.CLUSTERNAME ,ACCOUNT.URL, ACCOUNT.PORT);
            
            cassAct.initReadWirte(FRAUDCLICKKEYSPACE);
            MysqlDataManager mysql = new MysqlDataManager();            
            // start time
            ConfigUtil.setPathConfig("/home/bigdata/cpc/properties/conf.properties");
            DOMConfigurator.configure("/home/bigdata/cpc/properties/log4j.xml");
            
           // ConfigUtil.setPathConfig("E:\\config_fraud_click\\conf.properties");
           // DOMConfigurator.configure("E:\\config_fraud_click\\log4j.xml");
            // time
            //String currentDate = TimeUtil.getCurrentTimeInString();//2012-07-24
            String currentDate = HandleDataTableDomainDate.handleDate();//2012-07-24
            //String currentDate = CONSTANT.Date;
            String[] arrTime = new String[3];
            arrTime = removeSpaces(currentDate).split("-");
            Calendar endCalendar = Calendar.getInstance();
            endCalendar.set(Integer.valueOf(arrTime[0]), Integer.valueOf(arrTime[1])-1, Integer.valueOf(arrTime[2]), 23, 59, 55);
            endCalendar.set(Calendar.MILLISECOND, 0);
            
            List<FraudGuidInDateRangeResult> fraudGuidInSecRangeResults = new FraudCountByGuidInDate().countFraudGuidInDateSlice(5L, endCalendar.getTime());
            
            Debug.println("so guid khong hop le trong rule ngay:" +fraudGuidInSecRangeResults.size());
            Iterator it = fraudGuidInSecRangeResults.iterator();
            //String insertDate = "2012-07-07";
            StringBuilder sbff = new StringBuilder();
            
            while(it.hasNext())
            {
                FraudGuidInDateRangeResult value = (FraudGuidInDateRangeResult) it.next();
                
                //System.out.println("tong so click:" +value.getTotalClick());
                //System.out.println("guidid:" +value.getGuid());
                //System.out.println("date:" +value.getDateString());
                
                String str = cassAct.getFraudClickDay(value.getGuid()+"_"+value.getDateString(),ColumFamlyGuidDataContentBanneridData, currentDate);
                //check null
                 if(sbff.toString().length() > 100000)
                {                    
                    //xu li cho du lieu cuoi
                    String relStr = sbff.toString();
                    String valInsert = relStr.substring(0, (relStr.length()-1));                    
                    mysql.insertFraudClick(valInsert);
                    sbff.setLength(0);
                }                            
            }
            if(sbff.toString().length() > 1)
            {                    
                    //xu li cho du lieu cuoi
                    String relStr = sbff.toString();
                    String valInsert = relStr.substring(0, (relStr.length()-1));                    
                    mysql.insertFraudClick(valInsert);
                    sbff.setLength(0);
            } 
        //shut down connection
        mysql.shutdownConnection();

        } catch (Exception ex)
        {
            Debug.println("exception sucess rule 2:"+ex.getMessage());
        }
        long last_time = System.currentTimeMillis();        
        Debug.println("sucess rule 2");
        Debug.println("Thoi gian chay  :" +(last_time-first_time));
    }
    public static String removeSpaces(String s) {
      StringTokenizer st = new StringTokenizer(s," ",false);
      String t="";
      while (st.hasMoreElements()) t += st.nextElement();
      return t;
    }

    /*
     * Lay thoi gian tu 6h sang ngay hom truoc toi 5h59 sang ngay hom sau
     * Coi la 1 ngay
     */
    public String handleDate()
    {
        String retDate = "";//2012-07-24
        String date = TimeUtil.getCurrentTimeInStringForLog();//yyyy/MM/dd H:mm:ss

        String[] arrTime = new String[2];
        String[] firstArrTime = new String[3];
        String[] secondArrTime = new String[3];

        arrTime = date.split(" ");
        firstArrTime    = arrTime[1].split(":");
        secondArrTime   = arrTime[0].split("-");
        //init checkDate if trigger from 0h -> 6h
        if(checkFraudClickbyDay == 0)
        {
            checkFraudClickbyDay = TimeUtil.getCurrentTime();
        }

        if(Integer.valueOf(firstArrTime[0]) >= 6 && Integer.valueOf(firstArrTime[0]) <= 23)
        {
            checkFraudClickbyDay = TimeUtil.getCurrentTime();
            retDate = secondArrTime[0]+"-"+secondArrTime[1]+"-"+secondArrTime[2];
        } else if (Integer.valueOf(firstArrTime[0]) >= 0 && Integer.valueOf(firstArrTime[0]) < 6 && TimeUtil.getCurrentTime() >= checkFraudClickbyDay)
        {
            Debug.println(date + "_" + TimeUtil.getCurrentTime() + "_" + checkFraudClickbyDay);
            int day = Integer.valueOf(secondArrTime[2]) - 1;
            retDate = secondArrTime[0]+"-"+secondArrTime[1]+"-"+String.valueOf(day);
        }
        return retDate;
    }
}
